const { body } = require("express-validator");
const { status } = require("express/lib/response");
const { Article, User } = require("../model");
const path = require("path");
var multiparty = require("multiparty");
var fs = require("fs"); //文件模块
exports.listArticles = async (req, res, next) => {
  try {
    const { limit = 6, offset = 0, tag, author } = req.query;
    let filter;
    if (req.query.type) {
      filter = {
        type: req.query.type,
      };
    }

    // if (author) {
    //   const user = await User.findOne({ _id: author });
    //   filter.author = user ? user._id : null;
    // }

    //限制和分页
    const articles = await Article.find(filter)
      .skip(+offset) //跳过
      .limit(+limit) //取多少
      .sort({
        createdAt: -1, //倒序
      });
    const articlesCount = await Article.find(filter);
    
    console.log(articlesCount);
    res.status(200).json({
      articles,
      length: articlesCount.length,
    });
  } catch (err) {
    next(err);
  }
};

exports.getArticle = async (req, res, next) => {
  try {
    const article = await Article.findById(req.params.articleId).populate(
      "author"
    );
    if (!article) {
      return status(404).end();
    }
    res.status(200).json({
      article,
    });
  } catch (err) {
    next(err);
  }
};

exports.createArticle = async (req, res, next) => {
  try {
    console.log(req.body.article);
    const article = new Article(req.body.article);
    article.author = req.user._id;
    article.populate("author").execPopulate();
    await article.save();
    res.status(201).json({
      article,
    });
  } catch (err) {
    next(err);
  }
};

exports.updateArticle = async (req, res, next) => {
  try {
    const article = req.article;
    const bodyArticle = req.body.article;
    article.title = bodyArticle.title ? bodyArticle.title : article.title;
    article.description = bodyArticle.description || article.description;
    article.body = bodyArticle.body || article.body;
    article.image = bodyArticle.image || article.image;
    article.authorName = bodyArticle.authorName || article.authorName;
    console.log(article);
    await article.save();
    res.status(201).json({
      article,
    });
  } catch (err) {
    next(err);
  }
};

exports.deleteArticle = async (req, res, next) => {
  try {
    const article = req.article;
    await article.remove();
    res.status(204).end();
  } catch (err) {
    next(err);
  }
};

exports.sendPhoto = async (req, res, next) => {
  try {
    const photoName = req.body.name;
    const photoType = req.body.type;
    console.log(photoName);
    let PhotoPath = path.join(__dirname, "../public/postView", photoName);
    // console.log(PhotoPath)
    // console.log(req.body.base64Img)
    let dataBuffer = new Buffer.from(req.body.base64Img, "base64");
    fs.writeFile(PhotoPath, dataBuffer, function (err) {
      if (err) {
        console.log(err);
      } else {
        res.status(201).end();
      }
    });
  } catch (err) {
    next(err);
  }
};

exports.articlePhoto = async (req, res, next) => {
  try {
    var form = new multiparty.Form(); //实例化表单
    form.encoding = "utf-8";
    var photoname = "";
    form.uploadDir = path.join(__dirname, "../public/articleView");
    form.parse(req, function (err, fields, files) {
      try {
        console.log(files);
        photoname = files.image[0].path.split("\\").slice(-1);
        res.status(200).json({
          url: "http://localhost:3000/static/articleView/" + photoname,
          // url: 'http://127.0.0.1:3000/static/articleView/' + photoname,
        });
      } catch (error) {
        console.log(err);
      }
    });
  } catch (err) {
    next(err);
  }
};
